import threading
import time

"""
利用事件的处理来模拟一种异步操作
"""


num = 0
semap = threading.BoundedSemaphore(4)

def addNum():
    global num
    #获得锁
    semap.acquire()
    num += 1
    print('current num:', num)
    time.sleep(2)
    #释放锁
    semap.release()

def main():
    threads = []
    for i in range(40):
        t = threading.Thread(target=addNum)
        threads.append(t)
    for i in range(40):
        threads[i].start()
    for i in range(40):
        threads[i].join()
    print('final num: ', num)


if __name__ == '__main__':
    main()